#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import requests
import re
import urllib2
import os
import shutil
import sys
import time

class A:
    def __init__(self):
        pass

# 以后要支持断点续传
def http_download_internal(url, path = None):
    """
    Http下载
    :param url: 下载地址
    :param path: 本地存储地址
    :return: True表示下载成功，False表示下载失败
    """
    if not is_http_url(url):
        print('%s is not http url' % (url))
        return False

    # file to download
    f = None
    try:
        response = urllib2.urlopen(url)
        print("Response code: " + str(response.getcode()))
        info = response.info()
        headers = getattr(info, "headers")
        print(type(info))
        print("headers type is : " + str(type(headers)))
        print("headers: " + str(headers))
        print("Content-disposition value : " + str(info.getheaders("Content-disposition")))
        print "-------------------"
        print("info class is " + str(dir(info)))
        print "-------------------"
        print("Response info: " + str(info))
        if response.getcode() != 200:
            print("Response code is not 200, failed!")
            return False
        # get right file path
        if not path:
            filedir = os.getcwd()
            filename = url.split('/')[-1]
        else:
            filedir = os.path.dirname(path)
            filename = os.path.basename(path)

        if not os.path.exists(filedir):
            os.makedirs(filedir)
        path = os.path.join(filedir, filename)

        if os.path.exists(path):
            if os.path.isdir(path):
                shutil.rmtree(path)
            else:
                os.remove(path)

        f = open(path, 'wb')
        file_size = -1;
        buffer_size = 4096
        process = 0
        last_time_stamp = time.time()
        while True:
            buffer = response.read(buffer_size)
            if not buffer:
                break
            f.write(buffer)
            process += len(buffer)
            current_time_stamp = time.time()
            if current_time_stamp - last_time_stamp > 1.0:
                last_time_stamp = current_time_stamp
            print("%s bytes downloaded" % (str(process)))
    except urllib2.URLError:
        print("Error: %s : %s" % (sys.exc_info()[0], sys.exc_info()[1]))
        return False
    except IOError:
        print("Error: %s : %s" % (sys.exc_info()[0], sys.exc_info()[1]))
        return False
    finally:
        if f:
            f.close()

    return True



def is_http_url(url):
    url_regex = re.compile(
        r'^(?:http|ftp)s?://'  # http:// or https://
        r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|'  # domain...
        r'localhost|'  # localhost...
        r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})'  # ...or ip
        r'(?::\d+)?'  # optional port
        r'(?:/?|[/?]\S+)$', re.IGNORECASE)
    if url_regex.match(url):
        return True
    else:
        return False

if __name__ == "__main__":
    #http_download_internal("http://android-crash.amap.test:8111/repository/toolchain/1.0.0/qnx/default/abtor.xml")
    #http_download_internal("http://gitlab.alibaba-inc.com/AutoNavi_Engine/release_900/blob/master/AE9.0.0.1-201612131817-nolog.zip")
    #http_download_internal("http://gitlab.alibaba-inc.com/AutoNavi_Engine/release_900/raw/master/AE9.0.0.1-201612131817-nolog.zip")
    http_download_internal("http://gitlab.alibaba-inc.com/AutoNavi_Engine/release_900.git")
